/*
 * Copyright (c) 2025 CAX Conversion Project
 */
package com.comac.ins.bomt.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.comac.ins.bomt.domain.vo.SectionGroupItemVo;
import com.comac.ins.bomt.service.SectionService;
import com.comac.ins.common.core.domain.model.LoginUser;
import com.comac.ins.common.core.exception.BizException;
import com.comac.ins.common.core.utils.BizAssertUtil;
import com.comac.ins.common.json.utils.JsonUtils;
import com.comac.ins.isfd.domain.vo.IsfdModelManagementStructureDefinitionTreeNodeVo;
import com.comac.ins.isfd.service.IIsfdModelManagementStructureDefinitionTreeService;
import com.fasterxml.jackson.core.type.TypeReference;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 部段服务
 *
 * @author zhanghongyi
 * @date 2024 /8/27
 * @description SectionServiceImpl
 */
@RequiredArgsConstructor
@Service
@Slf4j
public class SectionServiceImpl implements SectionService {


    private final IIsfdModelManagementStructureDefinitionTreeService isfdModelManagementStructureDefinitionTreeService;
    /**
     * 默认配置
     * */
    private static final Map<String, List<String>> DEFAULT = JsonUtils.parseObject("""
        {
        "S11":["机头"],
        "S12":["前机身"],
        "S20":["中机身","中央翼"],
        "S31":["中后机身"],
        "S32":["机身尾段"],
        "S50":["垂直安定面","方向舵"],
        "S60":["水平安定面中央盒段"],
        "S70":["左机翼盒段","左机翼后缘及襟翼","左机翼前缘及缝翼"],
        "S80":["右机翼盒段","右机翼后缘及襟翼","右机翼前缘及缝翼"]
        }
        """, new TypeReference<>() {
    });


    @Override
    public Map<String, List<String>> getSectionGroupConfig(String aircraftModel) {
        Map<String, List<String>> result = getSectionConfig(aircraftModel);
        if (MapUtils.isEmpty(result)) {
            return DEFAULT;
        }
        return result;
    }

    /**
     * 获取逆部段分组配置
     */
    @Override
    public Map<String, String> getReverseSectionGroupConfig(String aircraftModel) {
        Map<String, List<String>> sectionGroupConfig = getSectionGroupConfig(aircraftModel);
        Map<String, String> reverseGroupConfig = new HashMap<>(10);
        for (Map.Entry<String, List<String>> entry : sectionGroupConfig.entrySet()) {
            for (String section : entry.getValue()) {
                reverseGroupConfig.put(section, entry.getKey());
            }
        }
        return reverseGroupConfig;
    }
    private Map<String, List<String>> getSectionConfig(String aircraftModel) {

        List<IsfdModelManagementStructureDefinitionTreeNodeVo> queryResult = isfdModelManagementStructureDefinitionTreeService.queryListTree();
        log.info("section group query result:{}", JsonUtils.toJsonString(queryResult));
        Map<String, List<IsfdModelManagementStructureDefinitionTreeNodeVo>> groupResult = queryResult.stream().collect(Collectors.groupingBy(IsfdModelManagementStructureDefinitionTreeNodeVo::getMark));
        if (groupResult.containsKey(aircraftModel)) {
            List<IsfdModelManagementStructureDefinitionTreeNodeVo> config = groupResult.get(aircraftModel).get(0).getChildren();
            Map<String, List<String>> result = config.stream().collect(Collectors.toMap(item -> {
                String[] keyTokens = StringUtils.split(item.getMark(), "_");
                if (keyTokens != null && keyTokens.length > 0) {
                    return keyTokens[keyTokens.length - 1];
                } else {
                    return "";
                }

            }, item -> {
                String[] valueTokens = StringUtils.split(item.getName(), ",");
                if (valueTokens != null && valueTokens.length > 0) {
                    return Arrays.asList(valueTokens);
                } else {
                    return new ArrayList<>();
                }
            }, (a, b) -> a));
            BizAssertUtil.notEmpty(result,"group config is empty");
            for(Map.Entry<String,List<String>> entry:result.entrySet()){
                BizAssertUtil.notNull(entry.getKey(),"isfd query result is invalid");
                if(CollectionUtils.isEmpty(entry.getValue())){
                    log.warn("isfd query result is invalid:{}", JsonUtils.toJsonString(queryResult));
                }
            }
            log.info("final group:size:{},config:{}", result.size(), JsonUtils.toJsonString(result));
            return result;
        } else {
            return null;
        }
    }
}
